package com.cunyme;

import java.io.IOException;
import java.util.Calendar;
import java.util.Map;
import java.util.Vector;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import android.app.ListActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class Schedule extends ListActivity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
  

        SQLiteDatabase cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        helper_functions helpers = new helper_functions();
		Map <String, String> portal_cookies = helpers.getcookies("portal", cuny_meDB);
		Map <String, String> esims_cookies = helpers.getcookies("esims", cuny_meDB);
		cuny_meDB.close();

        
    	//ScrollView announcements_layout = new ScrollView(this);
    	Vector<course> courses = new Vector<course>();
        try
        {
        	final Calendar c = Calendar.getInstance();
            int month = c.get(Calendar.MONTH) +1;
            int year = c.get(Calendar.YEAR);
            Log.i("month= ", Integer.toString(month));
            Log.i("year=", Integer.toString(year));

        	String url="https://esims.cuny.edu/LoggedInServlet?CurrentCommand=ScheduleDisplay&Term=";
        
        	if(month==6){
        		url+=year+"06";
        	}
        	if (month<=5){
        		url+=year+"02";
        	}
        	else if(month>7){
        		url+=year+"09";
        	}
        
            Log.i("url cutoff", url.substring(0, 79));
            // We establish a connection

        	
            Connection esims_conn = Jsoup.connect(url)
            .cookie("ObSSOCookie", portal_cookies.get("ObSSOCookie")).cookie("JSESSIONID", portal_cookies.get("JSESSIONID"))
            .cookie("BIGipServerportal_http_pl", portal_cookies.get("BIGipServerportal_http_pl"))
            .cookie("portalErrorCookie", portal_cookies.get("portalErrorCookie")).cookie("ObTEMP", portal_cookies.get("ObTEMP"))
            .cookie("JSESSIONID", esims_cookies.get("JSESSIONID"))
            .cookie("BIGipServeresims_new_http_pl", esims_cookies.get("BIGipServeresims_new_http_pl"));
            
            org.jsoup.nodes.Document doc = esims_conn.post();
            Element body = doc.body();
            String source = body.html();
            String save_source = source;
            Log.i("source length", Integer.toString(source.length()));
            
            if(source.length()<600){
            	
                Connection esims_conn2 = Jsoup.connect(url)
                .cookie("ObSSOCookie", portal_cookies.get("ObSSOCookie")).cookie("JSESSIONID", portal_cookies.get("JSESSIONID"))
                .cookie("BIGipServerportal_http_pl", portal_cookies.get("BIGipServerportal_http_pl"))
                .cookie("portalErrorCookie", portal_cookies.get("portalErrorCookie")).cookie("ObTEMP", portal_cookies.get("ObTEMP"))
                .cookie("JSESSIONID", esims_cookies.get("JSESSIONID"))
                .cookie("BIGipServeresims_new_http_pl", esims_cookies.get("BIGipServeresims_new_http_pl"));
                
                org.jsoup.nodes.Document doc2 = esims_conn2.post();
                Element body2 = doc2.body();
                String source2 = body2.html();
                source=source2;
                
                String tempurl = url.substring(0, 79);
                tempurl+="09";
   		source=save_source;
                
            }
            
            String SchedTDCrseInfo="<td class=\"SchedTDCrseInfo\" align=\"left\" width=\"16%\" valign=\"middle\" bgcolor=\"#dddddd\"> <b> "; //94

            
            for(int i=0; i<source.length()-92; i++){
            	String TDCrse_temp = source.substring(i, i+92);
            	
            	if(SchedTDCrseInfo.equals(TDCrse_temp)){	
            		course cunyCourse = new course();	//create new course
            		i+=92;
            		String course_name="";
            		while(!(source.substring(i, i+4).equals("</b>"))){
            			course_name+= source.substring(i, i+1);
            			i++;
            		}
            		cunyCourse.setName(course_name);	//add name to course
           	
            		int day_count= 0;
            			
            		while(!(source.substring(i, i+4).equals("<tr>"))){
            		
            			if(source.substring(i, i+5).equals("&nbsp")){
            				day_count++;
            			}
            			if(source.substring(i, i+6).equals("Start:")){
            				day_count++;
            				i+=6;	//to get to start time position
            				cunyCourse.setStart(source.substring(i, i+7));
            				i+=18;	//to get to end time position
            				cunyCourse.setEnd(source.substring(i, i+7));
            				i+=19;	//to get to room position
            				String room_name="";
            				while(!(source.substring(i, i+1).equals("<"))){
            					room_name+=source.substring(i,i+1);
            					i++;
            				}
            				cunyCourse.setRoom(room_name);
            				i+=12;	//to get to building position
            				String building="";
            				while(!(source.substring(i, i+1).equals("<"))){
            					building+=source.substring(i,i+1);
            					i++;
            				}
            				cunyCourse.setBuilding(building);
            				
            				String daystring="";
            				switch (day_count){
            					case 1: daystring="M";
            						break;
            					case 2: daystring="T";
            						break;
            					case 3: daystring="W";
            						break;
            					case 4: daystring="Th";
            						break;
            					case 5: daystring="F";
            						break;
            					case 6: daystring="S";
            						break;
            					case 7: daystring="Su";
            						break;
            				}
            				cunyCourse.setDays(daystring);
            			}		
            			i++;
            		}
            		courses.add(cunyCourse);
            	}
           
            }
            //Just some Log info used for debugging earlier on
            /*
            for(int i=0; i<courses.size(); i++){
            	Log.i("Name", courses.elementAt(i).getName());
            	Log.i("Start", courses.elementAt(i).getStart());
            	Log.i("End", courses.elementAt(i).getEnd());
            	Log.i("Room", courses.elementAt(i).getRoom());
            	Log.i("Building", courses.elementAt(i).getBuilding());
            	Log.i("Days", courses.elementAt(i).getDays());
            }*/
            if (courses.size()<1){
        		course cunyCourse = new course();
        		cunyCourse.setName("Cant find courses");
        		courses.add(cunyCourse);
            }
           
            String[] sched_classes = new String[courses.size()];	//declare size of array to the number of courses
       
            String temp="";
            for(int i=0; i<courses.size(); i++){
            	temp="Name: " + courses.elementAt(i).getName() + "\nStart: " 
            	+ courses.elementAt(i).getStart() + "\nEnd: " 
            	+ courses.elementAt(i).getEnd() + "\nDays: "
            	+ courses.elementAt(i).getDays() + "\nRoom: "
            	+ courses.elementAt(i).getRoom() + "\nBuilding: "
            	+ courses.elementAt(i).getBuilding();
            	sched_classes[i] = temp;
            }

            setContentView(R.layout.schedule);
            
            ArrayAdapter<String> scheduleAdapter;
            scheduleAdapter = new ArrayAdapter<String>(this, R.layout.list_for_sched, sched_classes);
            
            setListAdapter(scheduleAdapter);

        }
        


        
        catch (IOException e)
        {
        	Toast.makeText(getApplicationContext(), "Unable to Establish Connection.", Toast.LENGTH_SHORT).show();
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
